# smtplib 用于邮件的发信动作
import datetime
import json
import os
import smtplib
# email 用于构建邮件内容
from email.mime.text import MIMEText


class Stmp(object):
    def __init__(self, from_addr, to_addr, smtp_pwd):
        # 发信方的信息：发信邮箱，QQ 邮箱授权码
        self.from_addr = from_addr
        self.smtp_pwd = smtp_pwd
        # 收信方邮箱
        self.to_addr = to_addr
        # 发信服务器
        self.smtp_server = 'smtp.qq.com'

    def sent_mail(self, context):
        # 邮箱正文内容，第一个参数为内容，第二个参数为格式(plain 为纯文本)，第三个参数为编码
        msg = MIMEText(context, 'html', 'utf-8')
        msg["From"] = self.from_addr
        msg["Subject"] = "图书馆预约座位"
        try:
            server = smtplib.SMTP_SSL(self.smtp_server)
            server.connect(self.smtp_server, 465)
            server.login(self.from_addr, self.smtp_pwd)
            server.sendmail(self.from_addr, self.to_addr, msg.as_string())
            # 关闭服务器
            server.quit()
            return "-------------QQ邮箱推送成功-----------"
        except Exception as e:
            return "---------QQ邮箱推送失败------------"


if __name__ == '__main__':
    file = []
    if os.path.exists('./text.json'):
        with open('./text.json', 'r', encoding='utf-8') as f:
            file = json.load(f)

    for info in file:
        username = info['username']
        password = info['password']
        spaceId = info['spaceId']
        area = info['area']
        from_addr = info['from_addr']
        to_addr = info['to_addr']
        smtp_pwd = info['smtp_pwd']
        print(info['username'])
        smtp = Stmp(from_addr, to_addr, smtp_pwd)
        today = datetime.date.today()
        tomorrow = today + datetime.timedelta(days=1)
        context = "<div>邮箱测试:  <br>" + "时间：" + str(tomorrow) + " 座位：" + spaceId + "</div>"
        print(smtp.sent_mail(context))
